﻿//#define tic_tac
//Attention : double click higher 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class jump : MonoBehaviour
{
    public Rigidbody rigit_player;
    public int max_air_jump = 1;
    public float jumpHeight = 1f;

    float jump_time = 0;
    bool touch_ground_tag = false;
    bool touch_tag = false;

    // Start is called before the first frame update

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetButtonDown("Jump"))
        {
            StartCoroutine(jump_routine());
        }
    }

    IEnumerator jump_routine()//jetpack
    {
        if(touch_ground_tag || jump_time < max_air_jump)
        {
            jump_time++;
            Vector3 temp_velocity = rigit_player.velocity;
            temp_velocity.y += Mathf.Sqrt(-2f * Physics.gravity.y * jumpHeight);
            rigit_player.velocity = temp_velocity;
        }
        yield return null;
    }
    private void OnCollisionEnter(Collision collision)
    {
        touch_tag = true;
        EvaluateCollision(collision);
    }
    private void OnCollisionStay(Collision collision)
    {
        touch_tag = true;
        EvaluateCollision(collision);
    }
    private void OnCollisionExit(Collision collision)
    {
        touch_tag = false;
        touch_ground_tag = false;
    }
    void FixedUpdate()
    {
#if tic_tac
        if(touch_ground_tag||touch_tag)
        {
            jump_time = 0;
        }
#else
        if (touch_ground_tag)
        {
            jump_time = 0;
        }
#endif
    }
    void EvaluateCollision(Collision collision)
    {
        for (int i = 0; i < collision.contactCount; i++)
        {
            Vector3 coll_temp = collision.GetContact(i).normal;
            touch_ground_tag = touch_ground_tag | (coll_temp.y > 0.7);
        }
    }
}

